<template>
	<view class="joiner_box">
		<scroll-view @scrolltolower="scrolltolower" class="scroll-view_H" scroll-x="true" :lower-threshold="50"
			:scroll-left="scrollLeft">
			<template v-if="allJoinerData.length">
				<view class="scroll-view-item_H" v-for="item in allJoinerData" :key="item.user_id">
					<view 
						class="content content_default" 
						@click="clickJoinerFun(item)"
						:style="{
							background: item?.joinBgc?.bgc_url ? `url(${joinJoinBgcImg(item?.joinBgc?.bgc_url)})` : '',
							backgroundSize:'cover',
							backgroundPosition: 'center center'
						}"
					>
						<uni-badge class="uni-badge-left-margin" absolute="rightTop" :offset="[10, 0]" :text="item.admin_id === item.user_id ? '管' : ''"
							type="warning">
							<view class="avatar">
								<Avatar :fileName="item.user_avatar" size="70rpx" />
							</view>
						</uni-badge>
						<view 
							v-if="isScrollLower" 
							class="name text_ellipsis" 
							:style="{
								color: item?.joinBgc?.bgc_url ? item?.joinBgc?.font_color : primary_text_color
							}"
						>
							{{item.nick_name_by_dormitory}}
						</view>
					</view>
				</view>				
			</template>
			<view v-else class="loading_box">
				<uni-load-more content-text="加载中" iconType="circle" :color="primary_hot_color" status="loading" />
			</view>
		</scroll-view>
		<view class="hand" v-if="isShowHand">
			<MyIcons size="40rpx" :src="joinSystemPath('hand.png')" />
		</view>
		<MyPopub 
			:height="`${clickJoinerShowPopubNums ? 340 : 230}rpx`" 
			:isOpenPopub="openPopubFlag" 
			:slotsNums="clickJoinerShowPopubNums ? 3 : 2"
		>
			<template #1>
				<view class="pupub_item" @click="showClickJoinerTime">
					{{clickJoinerTime}}
				</view>
			</template>
			<template #2>
				<view v-if="isClickMine" class="pupub_item" style="width: calc(90vw);" @click="goJoinBgcList">
					设置我的皮肤
				</view>
				<view v-else class="pupub_item" style="width: calc(90vw);" @click="goJoinBgcList">
					ta的皮肤：{{chooseUser?.joinBgc?.name || '系统默认'}}
				</view>
			</template>
			<template v-if="clickJoinerShowPopubNums" #3>
				<view class="pupub_item" @click="iskickFun">
					踢出宿舍
				</view>
			</template>
			
		</MyPopub>
		<MyModal :openModalFlag="openModalFlag" :okFun="submitKick">
			<template #title>
				提示
			</template>
			<template #content>
				<view class="is_kick_user">
					确认要踢出
					<text class="kick_name">
						{{chooseUser?.nick_name_by_dormitory}}
					</text>
					吗？
				</view>
			</template>
		</MyModal>
	</view>
</template>

<script setup>
	import {
		onShow,
		onShareAppMessage
	} from '@dcloudio/uni-app'
	import {
		watch,
		ref,
		onMounted,
		computed
	} from 'vue'

	import Avatar from '@/components/Avatar/Avatar.vue'
	import MyPopub from '@/components/MyPopub/MyPopub.vue'
	import MyModal from '@/components/MyModal/MyModal.vue'

	import {
		dynamicStyleStore
	} from '@/stores/dynamicStyle.js'
	import {userStore} from '@/stores/user'
	
	import {
		DormitoryModel
	} from '@/service/model/dormitory.js'
	import {
		joinSystemPath,
		joinJoinBgcImg
	} from '@/utils/imgJoinName.js'
	
	import {verifyHandleEg} from '@/hooks/verify.js'
	
	const user_store=userStore()
	const dynamicStyle_store = dynamicStyleStore()
	const dormitoryModel = new DormitoryModel()

	const props = defineProps({
		isScrollLower: {
			type: Boolean,
			default: false
		},
		queryData: {
			type: Object
		}
	})

	const scrollLeft = ref(0)
	const handRight = ref('10%')
	const isShowHand = ref(!uni.getStorageSync('firstScrollJoinerHelp'))

	const data = ref([1, 2, 3, 4, 5])
	data.value.unshift('添加成员')
	const kickName = ref('')

	const popupRef = ref()
	const openPopubFlag = ref(0)
	const openModalFlag = ref(0)

	const JoinerTransition = 'all .3s linear'

	const nameMarginTop = ref('')

	const contentWidth = ref('100rpx')
	
	const dormitoryAllId=uni.getStorageSync('homeData')

	watch(() => props.isScrollLower, () => {
		if (!props.isScrollLower) { //到达顶部了
			nameMarginTop.value = ''
			contentWidth.value = '100rpx'
		} else {
			nameMarginTop.value = '-30rpx'
			contentWidth.value = '150rpx'
		}
	})

	const {
		primary_hot_color,
		primary_main_bgc,
		dormitory_cover_border_color,
		primary_text_color,
		primary_text_hot_color,
		joiner_color,
		info_bgc,
		dormitory_name_color,
		joiner_bgc,
		joiner_card_bgc
	} = dynamicStyle_store.dormitoryStyle
	
	//点击加入者展示多少个pupub
	const clickJoinerShowPopubNums = computed(()=>chooseUser.value?.admin_id === user_store.userInfo.id)
	//点击加入者是不是自己
	const isClickMine = computed(()=>chooseUser.value?.user_id === user_store.userInfo.id)
	//点击显示加入者加入的时间
	const clickJoinerTime = computed(()=>`${chooseUser.value?.createAt || '未知时间'}加入宿舍`)
	//点击加入者的时间 
	const showClickJoinerTime = ()=>{uni.$emit('tips',clickJoinerTime.value,'info')}

	//宿舍所有成员
	const allJoinerData = ref([])
	const limit = 10
	const page = ref(0)
	const isAllowScrollGet = ref(true)
	const addUserCardData = {
		"user_id": "1",
		"nick_name_by_dormitory": "邀请成员",
		"user_avatar": "addUser.png",
		"joinBgc":{
			bgc_url: "join_bgc_5125_1678529570058.jpeg",
			font_color: "#33465F",
			id: "f4290d3fb816da1c43e0f3910570f781",
			name: "系统默认",
		}
	}
	const getAllJoinerDataFun = async () => {
		if (!isAllowScrollGet.value) return
		const {
			dormitory_id
		} = uni.getStorageSync('homeData')

		const {
			data,
			success
		} = await dormitoryModel.getAllJoiner({
			limit,
			page: page.value,
			orderBy: 'createAt.asc'
		}, dormitory_id)
		if (success) {
			if (!allJoinerData.value.length) {
				allJoinerData.value.unshift(addUserCardData)
			}
			if (!data.length) {
				isAllowScrollGet.value = false
			}
			const tmpJoinerData = [...allJoinerData.value, ...data]
			const adminIndex = tmpJoinerData.findIndex(item=>item.user_id === item.admin_id)
			const tmpJoinerCache = JSON.parse(JSON.stringify(tmpJoinerData[1]))
			tmpJoinerData[1] = JSON.parse(JSON.stringify(tmpJoinerData[adminIndex]))
			tmpJoinerData[adminIndex]=tmpJoinerCache
			
			allJoinerData.value = tmpJoinerData
		} else {
			getAllJoinerMockDataFun()
		}
	}

	const chooseUser = ref()
	//点击了成员
	const clickJoinerFun = (item) => {
		verifyHandleEg()
		if (item.user_id === '1') {
			uni.navigateTo({
				url:`/pages/Dormitory/DormitoryInvite/DormitoryInvite?dormitory_id=${dormitoryAllId.dormitory_id}&share=true`
			})
		} else {
			chooseUser.value = item
			openPopubFlag.value = Math.random()
		}
	}

	//是否踢出成员
	const iskickFun = () => {
		const {user_id,admin_id} = chooseUser.value
		if(user_id === admin_id){
			uni.$emit('tips','该用户是管理员','warn')
			return
		}else if(admin_id !== user_store.userInfo.id){
			uni.$emit('tips','您不是管理员','warn')
			return
		}
		openPopubFlag.value = -Math.random()
		openModalFlag.value = Math.random()
	}
	//确认踢出成员
	const submitKick = async () => {
		const dormitory_id = uni.getStorageSync('homeData').dormitory_id
		const user_id = chooseUser.value.user_id

		verifyHandleEg()

		const {
			data,
			success
		} = await dormitoryModel.deleteKickUser({
			dormitory_id,
			user_id
		})

		if (success) {
			uni.$emit('tips', '成功踢出', 'success')
			init()
		}
	}

	//模拟示例成员
	const getAllJoinerMockDataFun = () => {
		allJoinerData.value = []
		for (let i = 0; i < 10; i++) {
			const item = {
				user_id: i,
				nick_name_by_dormitory: '您还未选择任何宿舍',
				user_avatar: 'avatar_init_3.jpg'
			}
			allJoinerData.value.push(item)
		}
		allJoinerData.value.unshift(addUserCardData)
	}

	const scrolltolower = () => {
		page.value++
		getAllJoinerDataFun()
	}

	//初次使用滚动引导用户
	const scrollJoinerHelpFun = () => {
		if (!isShowHand.value) return
		const timerByLeft = setInterval(() => {
			scrollLeft.value += 10
			handRight.value = (parseInt(handRight.value.split('%')[0]) + 3) + '%'
			if (scrollLeft.value >= 80) {
				uni.setStorageSync('firstScrollJoinerHelp', true)
				isShowHand.value = false
				clearInterval(timerByLeft)
				const timerByRight = setInterval(() => {
					scrollLeft.value -= 10
					if (scrollLeft.value <= 0) {
						clearInterval(timerByRight)
					}
				}, 30)
			}
		}, 70)
	}
	
	//去往皮肤列表
	const goJoinBgcList=()=>{
		openPopubFlag.value = -Math.random()
		uni.navigateTo({
			url:'/pages/Dormitory/JoinBgcs/JoinBgcs'
		})
	}

	const init = () => {
		allJoinerData.value = []
		page.value = 0
		isAllowScrollGet.value = true
		if (uni.getStorageSync('homeData')?.dormitory_id && uni.getStorageSync('token')) {
			getAllJoinerDataFun()
		} else {
			getAllJoinerMockDataFun()
		}
	}
	
	watch(()=>user_store.userInfo?.id,()=>{
		setTimeout(()=>{
			init()
		},300)
	})

	onShow(() => {
		scrollJoinerHelpFun()
		init()
	})
</script>

<style lang="less">
	.text_ellipsis {
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}

	.joiner_box {
		width: 100%;
		height: 220rpx;
		display: flex;
		align-items: center;
		background-color: v-bind(joiner_bgc);
		position: relative;
		.loading_box{
			position: absolute;
			top: 50%;
			transform: translate(0,-50%);
			width: 100%;
		}
		.is_kick_user{
			color: v-bind(primary_text_color);
		}

		.kick_name {
			color: v-bind(primary_text_hot_color) !important;
		}

		.scroll-view_H {
			white-space: nowrap;
			width: 100%;
			height: 100%;
		}

		.scroll-view-item_H {
			display: inline-block;
			font-size: 36rpx;
			height: 180rpx;
			position: relative;
			top: 50%;
			transform: translate(0, -50%);
			padding: 20rpx;

			.content {
				height: 100%;
				width: v-bind(contentWidth);
				border-radius: 20rpx;
				box-shadow:
					5px 3px 7px rgba(0, 0, 0, .4),
					-7px -7px 12px rgba(255, 255, 255, .9);
				display: flex;
				flex-wrap: wrap;
				justify-content: center;
				align-items: center;
				padding: 0 10rpx;
				font-size: 24rpx;
				transition: v-bind(JoinerTransition);
				background-size:cover;
				background-position: center center;
			}
			.content_default{
				background: v-bind(joiner_card_bgc);
				background-size:cover;
				background-position: center center;
			}
			.avatar {
				transition: v-bind(JoinerTransition);
				display: flex;
				justify-content: center;
				min-width: v-bind(contentWidth);
			}

			.name {
				margin-top: v-bind(nameMarginTop);
				transition: v-bind(JoinerTransition);
				text-align: center;
			}
		}

		.hand {
			position: absolute;
			right: v-bind(handRight);
		}
		.pupub_item{
			width: 100%;
			display: flex;
			justify-content: center;
		}
		.invite_joiner{
			margin: 0 !important;
			width: 100%;
			height: 100rpx;
			background-color: #FFFFFF !important;
			color: v-bind(primary_text_color);
			border: 0px solid #FFFFFF !important;
			font-size: 30rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
</style>
